import React from 'react';
import {
  SafeAreaView,
  StyleSheet,
  ScrollView,
  View,
  Text,
  StatusBar,
  Image,
  TouchableWithoutFeedback,
} from 'react-native';

import Icon from 'react-native-vector-icons/Ionicons';
import {Input} from 'react-native-elements';
import {screenRect} from '../../util/screen';
import {Colors} from 'react-native/Libraries/NewAppScreen';
import BSafeAreaViewPlugs from '../../baseUI/b-safe-area-view-plus/index'
import BNavigationBar from '../../baseUI/b-navigation-bar/index'

import API from '../../api/index';
import router from '../../util/router'
import BText from '../../baseUI/b-text';

export default class Home extends React.Component {
  state = {
    dList: [],
    search: '',
    categoryList: [],
    currentCategoryId: '',
  };

  updateSearch = (search) => {
    this.setState({search});
  };

  componentDidMount() {
    this.getCategory().then(() => {
      this.getProjectList();
    });
  }

  /**
   * 获取项目列表
   */
  getProjectList = () => {
    const formatDate = (value) => {
      if (!value) return ''
      value = value.toString()
      const arr = value.split('T')
      return arr[0] + ' ' + arr[1].substr(0, 8)
    }
    return API.getProjectList({
      appTypeId: this.state.currentCategoryId,
      pageIndex: 1,
      pageSize: 10,
    }).then((res) => {
      const list = res.data.list;
      list.forEach(dItem => {
        dItem.createTime = formatDate(dItem.createTime)
      })
      this.setState({
        dList: res.data.list,
      });
    });
  };

  /**
   * 获取项目分类
   */
  getCategory = () => {
    return API.projectCategory().then((res) => {
      this.setState({
        categoryList: res.data.list,
        currentCategoryId: res.data.list[0]['id'],
      });
    });
  };

  onIndexChange = (index) => {
    this.setState(
      {
        curIndex: index,
        currentCategoryId: this.state.categoryList[index].id,
      },
      () => {
        this.getProjectList(true);
      },
    );
    this.cateRef._children[index].measure((x, y, width, height, left, top) => {
      this.cateRef.measure((x1, y1, w1, h1, l1, t1) => {
        if (x > screenRect.width / 2) {
          let dest = x + width / 2 - screenRect.width / 2;
          if (dest < 0) dest = 0;
          this.scrollRef.scrollTo({
            x: dest,
            y: 0,
            animated: true,
          });
        } else {
          this.scrollRef.scrollTo({
            x: 0,
            y: 0,
            animated: true,
          });
        }
      });
    });
  };

  _onScroll = (e) => {};

  _renderCategoryList = () => {
    const list = this.state.categoryList;
    const _onClick = (element, index) => {
      if (this.state.currentCategoryId === element.id) {
        return;
      }
      this.setState(
        {
          currentCategoryId: element.id,
          pageIndex: 0,
          hasMore: true,
          curIndex: index,
        },
        () => {
          this.onIndexChange(index);
        },
      );
    };
    const listElement = list.map((element, index) => {
      const cls = [
        {
          lineHeight: 48,
          fontSize: 14,
          color: '#666',
        },
      ];
      let line = null;
      if (element.id === this.state.currentCategoryId) {
        cls.push({color: '#c82519'});
        line = (
          <View
            style={{
              zIndex: 5,
              width: 20,
              height: 3,
              marginTop: -6,
              borderRadius: 2,
              backgroundColor: '#c82519',
            }}
          />
        );
      }
      return (
        <View
          key={index}
          style={{
            marginHorizontal: 12,
            display: 'flex',
            alignItems: 'center',
            flexDirection: 'column',
          }}>
          <Text style={cls} onPress={() => _onClick(element, index)}>
            {element.name}
          </Text>
          {line}
        </View>
      );
    });
    return (
      <View style={{zIndex: 2, backgroundColor: '#fff', top: 0}}>
        <ScrollView
          style={{}}
          showsHorizontalScrollIndicator={false}
          horizontal={true}
          ref={(ref) => (this.scrollRef = ref)}>
          <View
            style={{display: 'flex', flexDirection: 'row'}}
            ref={(ref) => (this.cateRef = ref)}>
            {listElement}
          </View>
        </ScrollView>
      </View>
    );
  };

  renderDList = () => {
    return this.state.dList.map((dItem, key) => {
      return (
        <TouchableWithoutFeedback
          key={key}
          onPress={null}
          onPress={() => {
            router.goH5ProjectDetail({
              navigation: this.props.navigation,
              projectId: dItem.id
            })
          }}>
          <View style={styles.d_item} key={key}>
            <View style={styles.d_item_head}>
              <BText style={{ fontSize: 14 }}>{key + 1}. {dItem.title}</BText>
              <BText></BText>
            </View>
            <View style={styles.d_item_body}>
              <View style={styles.d_item_row}>
                <BText type="second">需求预算：</BText>
                <BText type="second">¥{dItem.reward / 100}</BText>
              </View>
              <View style={styles.d_item_row}>
                <BText type="second">技能要求：</BText>
                <BText type="second" numberOfLines={0} style={styles.d_item_requires}>
                  {dItem.requires}
                </BText>
              </View>
              <View style={styles.d_item_row}>
                <BText type="second">发布时间：</BText>
                <BText type="second">{dItem.createTime}</BText>
              </View>
            </View>
            <View style={styles.d_item_footer}>
              <View style={[styles.flex, styles.flex_auto]}>
                <Image
                  style={styles.d_item_avatar}
                  source={{uri: dItem.userInfo.avatar}}></Image>
                <BText type="second">{dItem.userInfo.nickname}</BText>
              </View>
              <View style={styles.flex}>
                <BText type="second">{dItem.enrollList.length}人报名</BText>
              </View>
            </View>
          </View>
        </TouchableWithoutFeedback>
      );
    });
  };

  render() {
    return (
      <BSafeAreaViewPlugs
        style={{backgroundColor: '#fff', display: 'flex', flex: 1}}>
        <TouchableWithoutFeedback
          onPress={() => {
            this.props.navigation.push('Search');
          }}>
          <View style={styles.search_box}>
            <Icon
              name="search"
              size={18}
              color="#888"
              style={{
                marginRight: 6,
              }}
            />
            <Text style={{color: '#888'}}>搜索关键字</Text>
          </View>
        </TouchableWithoutFeedback>
        {this._renderCategoryList()}
        <View style={{backgroundColor: 'red', flex: 1}}>
          <ScrollView
            contentInsetAdjustmentBehavior="automatic"
            contentContainerStyle={{flexGrow: 1}}
            style={styles.scrollView}>
            <View style={styles.dList}>{this.renderDList()}</View>
          </ScrollView>
        </View>
      </BSafeAreaViewPlugs>
    );
  }
}

const styles = StyleSheet.create({
  scrollView: {
    backgroundColor: Colors.lighter,
    flex: 1,
  },
  search_box: {
    display: 'flex',
    flexDirection: 'row',
    marginHorizontal: 10,
    height: 32,
    alignItems: 'center',
    paddingLeft: 10,
    borderRadius: 16,
    // marginBottom: 10,
    backgroundColor: '#f4f4f4',
  },
  dList: {
    flex: 1,
    padding: 12,
    backgroundColor: '#f5f5f5',
  },
  d_item: {
    padding: 10,
    backgroundColor: '#fff',
    marginBottom: 10,
    borderRadius: 6,
  },
  d_item_row: {
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'flex-start',
    paddingBottom: 6,
    fontSize: 12,
    lineHeight: 18,
  },
  d_item_head: {
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'space-between',
    fontSize: 14,
    marginBottom: 10,
  },
  flex: {
    display: 'flex',
    flexDirection: 'row',
    alignItems: 'center',
  },
  flex_auto: {
    flex: 1,
  },
  d_item_body: {},
  d_item_avatar: {
    width: 28,
    height: 28,
    borderRadius: 14,
    marginRight: 8,
  },
  d_item_footer: {
    display: 'flex',
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    marginTop: 10,
    paddingTop: 10,
    borderTopWidth: 1,
    borderTopColor: '#f5f5f5',
  },
  d_item_requires: {
    overflow: 'hidden',
    flex: 1,
  },
  lh_sm: {
    lineHeight: 18,
  },
});
